package com.uyayo.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uyayo.blog.entity.BlogTag;
import com.uyayo.blog.mapper.BlogTagMapper;
import com.uyayo.blog.model.BlogTagCondition;
import com.uyayo.blog.service.BlogTagService;
import com.uyayo.framework.core.service.impl.BaseServiceImpl;
import com.uyayo.framework.pagehelper.Pageable;
import com.uyayo.framework.pagehelper.SortOrder;
import com.uyayo.framework.pagehelper.SortOrderHelper;
import com.uyayo.framework.pagehelper.SortOrderMapping;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.ArrayList;
import java.util.List;

@Service("blogTagService")
public class BlogTagServiceImpl extends BaseServiceImpl<BlogTag> implements BlogTagService {

	private final BlogTagMapper blogTagMapper;

	public BlogTagServiceImpl(BlogTagMapper blogTagMapper ) {
		this.blogTagMapper = blogTagMapper;
	}

	@Override
	public List<BlogTag> selectBlogTag(BlogTagCondition blogTagCondition) {
		Example example = new Example(BlogTag.class);
		example.createCriteria();
		return blogTagMapper.selectByExample(example);
	}
	
	@Override
	public PageBean<BlogTag> selectBlogTagByPaging(Pageable<BlogTagCondition> pageable) {

		List<BlogTag> userList;
		//分页处理
		List<SortOrderMapping> sortOrderMappers = new ArrayList<>();
		sortOrderMappers.add(new SortOrderMapping("createTime", "create_time"));
		sortOrderMappers.add(new SortOrderMapping("updateTime", "update_time"));

		List<SortOrder> sortOrders = pageable.getSortOrders();
		String orderBy = SortOrderHelper.getOrderBy(sortOrderMappers, sortOrders);

		PageHelper.startPage(pageable.getCurrentPage(), pageable.getPageSize());
		
		Example example = new Example(BlogTag.class);
		if(!StringUtils.isEmpty(orderBy)){
			example.setOrderByClause(orderBy);
		}
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(pageable.getCondition().getName())){
			criteria.andLike("name","%"+pageable.getCondition().getName()+"%");
		}
		if(pageable.getCondition().getBeginCreateTime()!=null || pageable.getCondition().getEndCreateTime()!=null){
			criteria.andBetween("createTime", pageable.getCondition().getBeginCreateTime(), pageable.getCondition().getEndCreateTime());
		}
		userList = blogTagMapper.selectByExample(example);

		//取记录总条数
		PageInfo<BlogTag> pageInfo = new PageInfo<>(userList);
		return new PageBean<BlogTag>(pageInfo.getTotal(),userList);
	}
	

	@Override
	public int saveBlogTag(BlogTag blogTag) {
		return blogTagMapper.insertSelective(blogTag);
	}

	@Override
	public int updateBlogTag(BlogTag blogTag) {
		return blogTagMapper.updateByPrimaryKeySelective(blogTag);
	}
}
